package view;

import interfaces.ViewPanel;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import utils.CommandGenerator;
import utils.KeyboardManager;

import com.toedter.calendar.JDateChooser;

import control.IncomeManager;
import control.MemberManager;
import control.Search;
import control.Shell;
import control.ValidateInput;
import control.ViewPanelManager;
import domain.Expense;
import domain.FamilyMember;
import domain.Income;
import enums.Frequency;

//@author A0098891H
public class IncomeManagerPanel extends BackgroundPanel implements ViewPanel  {
		public 	DefaultComboBoxModel<FamilyMember> cbm_incomeMember;
		
		private JDateChooser calendarDate;
		private JLabel lbl_incomeName;
		private JTextField txt_incomeName;
		private JLabel lbl_incomeAmount;
		private JTextField txt_incomeAmount;
		private JLabel lbl_incomeByMember;
		private JComboBox<FamilyMember> cb_incomeByMem;
		private JLabel lbl_incomePayer;
		private JTextField txt_incomePayer;
		private JLabel lbl_incomeDescr;
		private JTextField txt_incomeDescr;
		private JLabel lbl_incomeDate;
		private JTextField txt_incomeDate;
		private JLabel lbl_incomeFrequency;
		private JComboBox<Frequency> cb_incomeFrequency;
		private JTable incomeTable;
		private Vector<Vector> incomeRowData;
		
		private JScrollPane scrollPane_incomeList;
		
		private JButton btn_addIncome;
		private JButton btn_deleteIncome;
		private JButton btn_editIncome;
		private JButton btnStopUpdate;
		private JButton btn_cancelEdit;
		private JButton btn_saveEdit;
		
		private IncomeManager _incomeManager;
		private Shell _shell;
		private SidePane _sidePane;
		private MemberManager _memManager;
		private Search search;
		private ViewPanelManager _tabPanelMgr;
		private JButton btnAddMem;
		

		public IncomeManagerPanel(final IncomeManager incomeManager,final Shell shell,
				final MemberManager memManager,  SidePane sidePane, ViewPanelManager tabPanelMgr)
		{
			super();
			this.setLayout(null);
			
			_incomeManager = incomeManager;
			_shell = shell;
			_memManager = memManager;
			_sidePane = sidePane;
			_tabPanelMgr = tabPanelMgr;
			
			lbl_incomeName = new JLabel("Name");
			lbl_incomeName.setBounds(27, 14, 122, 17);
			this.add(lbl_incomeName);

			txt_incomeName = new JTextField();
			txt_incomeName.setColumns(10);
			txt_incomeName.setBounds(27, 38, 131, 23);
			this.add(txt_incomeName);
			
			lbl_incomeAmount = new JLabel("Amount");
			lbl_incomeAmount.setBounds(27, 65, 122, 17);
			this.add(lbl_incomeAmount);
			
			txt_incomeAmount = new JTextField();
			txt_incomeAmount.setColumns(10);
			txt_incomeAmount.setBounds(27, 86, 131, 23);
			this.add(txt_incomeAmount);

			lbl_incomeByMember = new JLabel("By Member");
			lbl_incomeByMember.setBounds(27, 120, 122, 17);
			this.add(lbl_incomeByMember);
			
			cb_incomeByMem = new JComboBox<FamilyMember>();//add member
			cb_incomeByMem.setBounds(27, 139, 131, 23);
			this.add(cb_incomeByMem);
			
			lbl_incomePayer = new JLabel("Payer");
			lbl_incomePayer.setBounds(27, 173, 122, 17);
			this.add(lbl_incomePayer);
			
			txt_incomePayer = new JTextField();
			txt_incomePayer.setColumns(10);
			txt_incomePayer.setBounds(27, 189, 131, 23);
			this.add(txt_incomePayer);

			lbl_incomeDescr = new JLabel("Description");
			lbl_incomeDescr.setBounds(170, 16, 83, 18);
			this.add(lbl_incomeDescr);
			
			txt_incomeDescr = new JTextField();
			txt_incomeDescr.setColumns(10);
			txt_incomeDescr.setBounds(248, 14, 400, 21);
			this.add(txt_incomeDescr);
			
			lbl_incomeDate = new JLabel("Date");
			lbl_incomeDate.setBounds(660, 14, 38, 17);
			this.add(lbl_incomeDate);
			
			//txt_incomeDate = new JTextField();
			//txt_incomeDate.setColumns(10);
			//txt_incomeDate.setBounds(557, 10, 122, 23);
			//this.add(txt_incomeDate);
			calendarDate = new JDateChooser();
			calendarDate.setBounds(698, 11, 122, 23);
			calendarDate.setPreferredSize(new Dimension(90,20));
			calendarDate.setDateFormatString("dd/MM/yyyy");
			this.add(calendarDate);
			

			lbl_incomeFrequency = new JLabel("Frequency");
			lbl_incomeFrequency.setBounds(27, 223, 112, 17);
			this.add(lbl_incomeFrequency);
			
			cb_incomeFrequency = new JComboBox<Frequency>();
			cb_incomeFrequency.addItem(Frequency.NO);
			cb_incomeFrequency.addItem(Frequency.DAILY);
			cb_incomeFrequency.addItem(Frequency.WEEKLY);
			cb_incomeFrequency.addItem(Frequency.MONTHLY);
			cb_incomeFrequency.addItem(Frequency.YEARLY);
			cb_incomeFrequency.setBounds(27, 242, 131, 23);
			this.add(cb_incomeFrequency);
			
			
			scrollPane_incomeList = new JScrollPane();
			scrollPane_incomeList.setBounds(170, 47, 650, 400);
			this.add(scrollPane_incomeList);
			
			
			search = new Search(_incomeManager);
			UneditableTable vectorTable = new UneditableTable(null, Search.getToIncomeVectorColName());
			incomeTable = new JTable(vectorTable);
			incomeTable.setFont(new Font("Tahoma", Font.BOLD, 11));
			scrollPane_incomeList.setViewportView(incomeTable);
			
			
			btn_addIncome = new JButton("Add Income");
			btn_addIncome.setBounds(175, 470, 122, 23);
			this.add(btn_addIncome);
			btn_addIncome.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					if(!validateInput())
						return;
					String cmd = CommandGenerator.getAddIncomeCmd(
							txt_incomeName.getText(), 
							Double.parseDouble(txt_incomeAmount.getText()), 
							((FamilyMember)cb_incomeByMem.getSelectedItem()).get_id(), 
							txt_incomePayer.getText(), 
							cb_incomeFrequency.getSelectedItem().toString(),
							((JTextField)calendarDate.getDateEditor().getUiComponent()).getText(), 
							txt_incomeDescr.getText());
					shell.readCmd(cmd);
					updateTable();
					setDefault();
				}
			});

			btn_deleteIncome = new JButton("Delete Income");
			btn_deleteIncome.setBounds(687, 470, 122, 23);
			this.add(btn_deleteIncome);
			btn_deleteIncome.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					int selectedRow = incomeTable.getSelectedRow();
					if(selectedRow>=0)
					{
						int incomeId = search.getIncomeIdList().get(selectedRow);
						String cmd = CommandGenerator.getDeleteIncomeCmd(incomeId);		
						shell.readCmd(cmd);
						updateTable();
						
					}
					else
					{
						print("Please select an existing income to delete.\n");
					}
					
				}
				
			});

			btn_editIncome = new JButton("Edit Income");
			btn_editIncome.setBounds(427, 470, 122, 23);
			this.add(btn_editIncome);
			
			btn_saveEdit = new JButton();
			btn_saveEdit.setIcon(new ImageIcon(IncomeManagerPanel.class.getResource("/images/save.png")));
			btn_saveEdit.setBounds(375, 458, 48, 48);
			btn_saveEdit.setVisible(false);
			btn_saveEdit.setBorderPainted(false);
			btn_saveEdit.setContentAreaFilled(false);
			btn_saveEdit.setFocusable(false);
			add(btn_saveEdit);
			
			btn_cancelEdit = new JButton();
			btn_cancelEdit.setIcon(new ImageIcon(IncomeManagerPanel.class.getResource("/images/cancel.png")));
			btn_cancelEdit.setBounds(553, 458, 48, 48);
			btn_cancelEdit.setVisible(false);
			btn_cancelEdit.setBorderPainted(false);
			btn_cancelEdit.setContentAreaFilled(false);
			btn_cancelEdit.setFocusable(false);
			add(btn_cancelEdit);
			
			btnStopUpdate = new JButton("Stop Update");
			btnStopUpdate.setVisible(false);
			btnStopUpdate.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					btnStopUpdate.setVisible(false);
					/*cb_expenseFrequency.addItem(Frequency.STOPPED);
					cb_expenseFrequency.setSelectedItem(Frequency.STOPPED);*/
					int selectedRow = incomeTable.getSelectedRow();
					int editId = search.getIncomeIdList().get(selectedRow);
					Income income = incomeManager.get(editId);
					income.set_frequency(Frequency.STOPPED);
					updateTable();
					setDefault();
				}
			});
			btnStopUpdate.setBounds(27, 282, 131, 23);
			add(btnStopUpdate);
			
			btnAddMem = new JButton("");
			btnAddMem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					KeyboardManager.genKeyEvent(KeyEvent.KEY_PRESSED, KeyEvent.CTRL_DOWN_MASK, KeyEvent.VK_M);
				} 
			});
			btnAddMem.setBorderPainted(false);
			btnAddMem.setContentAreaFilled(false);
			btnAddMem.setFocusable(false);
			btnAddMem.setIcon(new ImageIcon(IncomeManagerPanel.class.getResource("/images/user_add.png")));
			btnAddMem.setBounds(3, 138, 24, 24);
			add(btnAddMem);
		
			btn_editIncome.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					int selectedRow = incomeTable.getSelectedRow();
					if(selectedRow>=0)
					{
						int editId = search.getIncomeIdList().get(selectedRow);
						Income income = incomeManager.get(editId);
						txt_incomeName.setText(income.get_name());
						txt_incomeAmount.setText(income.get_amount()+"");
						cb_incomeByMem.setSelectedItem(income.get_byMem());
						txt_incomePayer.setText(income.get_partyInvolved());
						txt_incomeDescr.setText(income.get_comments());
						((JTextField)calendarDate.getDateEditor().getUiComponent()).setText(income.get_date().toString());
						cb_incomeFrequency.setSelectedItem(income.get_frequency());
						btn_saveEdit.setVisible(true);
						btn_cancelEdit.setVisible(true);
						btn_cancelEdit.setVisible(true);
						if(isPeriod(income.get_frequency()))
						{
							btnStopUpdate.setVisible(true);
						}
						else
						{
							btnStopUpdate.setVisible(false);
						}
					}
					else
					{
						print("Please select an existing income to edit.\n");
					}
				}
			});
			btn_saveEdit.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					int selectedRow = incomeTable.getSelectedRow();
					if(selectedRow>=0)
					{

						if(!validateInput())
							return;
						int editId = search.getIncomeIdList().get(selectedRow);
						//System.out.println("Edit id: "+ editId);
						String cmd = CommandGenerator.getEditIncomeCmd(
								editId,
								txt_incomeName.getText(), 
								Double.parseDouble(txt_incomeAmount.getText()), 
								((FamilyMember)cb_incomeByMem.getSelectedItem()).get_id(),
								txt_incomePayer.getText(), 
								cb_incomeFrequency.getSelectedItem().toString(),
								((JTextField)calendarDate.getDateEditor().getUiComponent()).getText(), 
								txt_incomeDescr.getText());

						//println("CMD: "+ cmd);
						shell.readCmd(cmd);
						updateTable();
						btn_saveEdit.setVisible(false);
						btn_cancelEdit.setVisible(false);
						btnStopUpdate.setVisible(false);
						setDefault();
						
					}
					else
					{
						print("Please select an existing income to edit.\n");
					}
				}
				
			});

			btn_cancelEdit.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					setDefault();
					btn_saveEdit.setVisible(false);
					btn_cancelEdit.setVisible(false);
					btnStopUpdate.setVisible(false);
				}
				
			});
			
			this.setDefault();
			this.updateAll();
		
		}
		
		//need to add search set
		
		/**
		 * 
		 * @Precondition 
		 * @Postcondition 
		 */
		public void setDefault()
		{
			txt_incomeName.setText("");
			txt_incomeAmount.setText("");
			cb_incomeByMem.setSelectedItem(_memManager.get(0));
			txt_incomePayer.setText(Income.DEFAULT_PAYER);
			txt_incomeDescr.setText(Income.DEFAULT_COMMENTS);
			((JTextField)calendarDate.getDateEditor().getUiComponent()).setText("");
			cb_incomeFrequency.removeItem(Frequency.STOPPED);
			cb_incomeFrequency.setSelectedItem(Income.DEFAULT_FREQUENCY);

		}

		
		/**
		 * 
		 * @Precondition 
		 * @Postcondition 
		 */
		public void updateAll()
		{			
			updateMember();
			updateTable();
		}
		
		public void updateMember()
		{
			cbm_incomeMember = new DefaultComboBoxModel<FamilyMember>();
			for(FamilyMember mem: _memManager.getList())
			{
				cbm_incomeMember.addElement(mem);
			}
			cb_incomeByMem.setModel(cbm_incomeMember);	
		}
		
		public void updateTable()
		{
			incomeRowData = search.toIncomeVector();
			UneditableTable vectorTable = new UneditableTable(incomeRowData, Search.getToIncomeVectorColName());
			incomeTable = new JTable(vectorTable);
			incomeTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			incomeTable.addMouseListener(new MouseAdapter() {
				   public void mousePressed(MouseEvent e) {
					      if (e.getClickCount() > 1) {
					         JTable target = (JTable)e.getSource();
					         int row = target.getSelectedRow();
					         int column = target.getSelectedColumn();
					         incomeTable.removeEditor();
					         // do some action
					         btn_editIncome.doClick();
					         }
					   }
					});
			for(int i=0;i<incomeTable.getColumnCount();i++)
			{
				incomeTable	.getColumnModel().getColumn(i).setMinWidth(120);
			}
			scrollPane_incomeList.setViewportView(incomeTable);
			incomeTable.setRowSelectionAllowed(true);
			_sidePane.update();
			_tabPanelMgr.updateIncome();
		}
		
		public boolean validateInput()
		{
			if(!ValidateInput.validName(txt_incomeName.getText()))
			{
				return false;
			}
			if(!ValidateInput.validAmount(txt_incomeAmount.getText()))
			{
				return false;
			}
			if(!ValidateInput.validPartyInvolved(txt_incomePayer.getText(),"Payer"))
			{
				return false;
			}
			if(!ValidateInput.validDescription(txt_incomeDescr.getText(),"Description"))
			{
				return false;
			}
			if(!ValidateInput.validDate(calendarDate, "Date")) {
				return false;
			}
			
			return true;
		}
		
		private boolean isPeriod(Frequency get_frequency) {
			// TODO Auto-generated method stub
			boolean index=false;
			switch(get_frequency)
			{
			    case DAILY:   
			    case WEEKLY:
			    case MONTHLY:
			    case YEARLY:  index = true;
			}
			return index;
		}
		
		public void print(String msg)
		{
			_sidePane.appendRecent(msg);
		}

		@Override
		public void updateExpense() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void updateIncome() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void updateLoan() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void updateCategory() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void updatePayMethod() {
			// TODO Auto-generated method stub
			
		}
		
	}

